#ifndef SAFEQUEUE_H
#define SAFEQUEUE_H

#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>

template <typename T>
class SafeQueue {
private:
    std::queue<T> m_queue;
    mutable std::mutex m_mutex;
    std::condition_variable m_condition;
    size_t m_maxSize;  // 队列最大容量

public:
    // 构造函数，指定最大容量（默认我给个40000）
    explicit SafeQueue(size_t maxSize = 40000) : m_maxSize(maxSize) {}
    SafeQueue(const SafeQueue&) = delete;
    SafeQueue& operator=(const SafeQueue&) = delete;

    // 入队操作，如果队列已满则返回false
    bool enqueue(const T& item) {
        std::lock_guard<std::mutex> lock(m_mutex);

        // 如果队列已满，返回false表示入队失败
        if (m_queue.size() >= m_maxSize) {
            return false;
        }

        m_queue.push(item);
        m_condition.notify_one();  // 通知等待的线程
        return true;
    }

    // 出队操作，支持超时
    bool dequeue(T& item, int timeoutMs = -1) {
        std::unique_lock<std::mutex> lock(m_mutex);

        if (timeoutMs >= 0) {
            // 超时等待
            if (!m_condition.wait_for(lock, std::chrono::milliseconds(timeoutMs),
                [this]() { return !m_queue.empty(); })) {
                return false;  // 超时
            }
        } else {
            // 无限等待直到队列非空
            m_condition.wait(lock, [this]() { return !m_queue.empty(); });
        }

        item = m_queue.front();
        m_queue.pop();
        return true;
    }

    // 检查队列是否为空
    bool isEmpty() const {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_queue.empty();
    }

    // 获取队列当前大小
    size_t size() const {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_queue.size();
    }

    // 获取队列最大容量
    size_t maxSize() const {
        std::lock_guard<std::mutex> lock(m_mutex);
        return m_maxSize;
    }

    // 设置队列最大容量
    void setMaxSize(size_t maxSize) {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_maxSize = maxSize;
    }

    // 清空队列
    void clear() {
        std::lock_guard<std::mutex> lock(m_mutex);
        while (!m_queue.empty()) {
            m_queue.pop();
        }
    }
};

#endif // SAFEQUEUE_H
